<script setup>
import { Upload, Delete, View, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { draftApi } from '@/api/draft/index'
import { dateFormatter } from '@/utils/formatTime'
import videoPlayDialog from './videoPlayDialog.vue'
import { updateFile } from '@/api/infra/file'
import { useUserStore } from '@/store/modules/user'



const userStore = useUserStore()
const userInfo = computed(() => userStore.user)
// 表单数据
const fusionForm = reactive({
  video1File: null,
  video2File: null,
  title: '',
  videoRemark: ''
})
let cacheUserVideos = ref({})

// 融合按钮加载状态
const fusionLoading = ref(false)
const isLock = ref(false)   //是否加锁

const pagination = ref({
  total: 0,
  pageSize: 20,
  pageSizes: [10, 20, 30, 40],
  pageNo: 1
})

const videoDialogRef = ref()

const timer = ref(null)

// 融合任务列表
const fusionTaskList = ref([])

// 文件选择处理
const handleFileChange = (file, videoType) => {
  console.log(`${videoType} file:`, file)

  if (file.status === 'ready') {
    // 验证文件
    if (file.raw.size > 1024 * 1024 * 1024 * 2) {
      // 2GB 限制
      ElMessage.warning('文件大小不能超过2GB')
      return
    }

    if(videoType === 'video1') {
      // 调用上传获取url
      updateFile({file: file.raw, directory: 'dy'}).then(res => {
        console.log(res.data)
        cacheUserVideos.value[userInfo.value.id] = {
          isLock: isLock.value == 1,
          url: res.data,
          name: file.raw.name
        }
        localStorage.setItem('cacheUserVideos', JSON.stringify(cacheUserVideos.value))
      })
    }

    // 直接存储文件
    fusionForm[`${videoType}File`] = file.raw
    ElMessage.success(`${videoType === 'video1' ? '第一个' : '第二个'}视频文件选择成功`)
  }
}

// 视频融合
const handleVideoFusion = () => {
  // 表单验证
  if(cacheUserVideos.value[userInfo.value.id].isLock && cacheUserVideos.value[userInfo.value.id].url) {} else {
    if (!fusionForm.video1File) {
      ElMessage.warning('请上传第一个视频文件')
      return
    }
  }
  if (!fusionForm.video2File) {
    ElMessage.warning('请上传第二个视频文件')
    return
  }
  fusionLoading.value = true
  console.log('handleVideoFusion', fusionForm)
  let url = URL.createObjectURL(fusionForm.video2File)
  const a = document.createElement('a');
  a.href = url
  a.download = fusionForm.video2File.name
  document.body.appendChild(a) // Firefox 要求插入 DOM
  a.click()
  document.body.removeChild(a)
   // 设置3-6秒的随机时间
  const randomTime = Math.floor(Math.random() * (6000 - 3000 + 1)) + 3000;
  setTimeout(() => {
    fusionLoading.value = false
    ElMessage.success('操作成功')
  }, randomTime)
}

function getList() {
  draftApi
    .getMaskList({
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.pageNo
    })
    .then((res) => {
      console.log('res', res)
      fusionTaskList.value = res.list
      pagination.value.total = res.total
    })
}

const downLoadPath = ref('')
function openDirectoryDialog() {
  // 添加调试信息
  console.log('openDirectoryDialog function called');
  
  // 直接检查 electronApi 是否存在，这是最可靠的检测方法
  if (!window.electronApi) {
    console.log('window object keys:', Object.keys(window));
    ElMessage.error('Electron API不可用');
    return;
  }
  
  // 检查 openDirectoryDialog 方法是否存在
  if (!window.electronApi.openDirectoryDialog) {
    console.error('openDirectoryDialog method is not available');
    ElMessage.error('打开目录对话框功能不可用');
    return;
  }
  
  console.log('Calling window.electronApi.openDirectoryDialog()');
  
  // 使用 contextBridge 暴露的 API 而不是直接使用 ipcRenderer
  window.electronApi.openDirectoryDialog().then(path => {
    console.log('Received response from openDirectoryDialog:', path);
    if (path) {
      downLoadPath.value = path
      localStorage.setItem('downLoadPath', path)
      console.log('Selected directory:', path)
      ElMessage.success('目录选择成功: ' + path)
      // 添加提示，说明下载文件将保存到此目录
      ElMessage.info('下载文件将保存到此目录')
    } else {
      console.log('未选择目录或操作已取消')
      // ElMessage.info('未选择目录或操作已取消')
    }
  }).catch(err => {
    console.error('Error selecting directory:', err)
    ElMessage.error('选择目录时出错: ' + (err.message || err))
  })
}

// 初始化第一个视频
function initCacheUserVideo() {
  if(localStorage.getItem('cacheUserVideos')) {
    cacheUserVideos.value = JSON.parse(localStorage.getItem('cacheUserVideos'))
  } else {
    cacheUserVideos.value[userInfo.value.id] = {
      isLock: false,
      url: '',
      name: ''
    }
    localStorage.setItem('cacheUserVideos', JSON.stringify(cacheUserVideos.value))
  }
  if(cacheUserVideos.value[userInfo.value.id] && cacheUserVideos.value[userInfo.value.id].isLock) {
    isLock.value = 1
  } else {
    isLock.value = 0
  }
  
}

function handleClickLock() {
  cacheUserVideos.value = JSON.parse(localStorage.getItem('cacheUserVideos'))
  console.log('isLock.value', isLock.value)
  // isLock.value = (isLock.value == 1) ? 1 : 0
  console.log('isLock.value2', isLock.value)
  cacheUserVideos.value[userInfo.value.id].isLock = isLock.value == 1
  localStorage.setItem('cacheUserVideos', JSON.stringify(cacheUserVideos.value))
}

// 启动已有任务的进度模拟
onMounted(() => {
  getList()
  timer.value = setInterval(() => {
    getList()
  }, 30000)
  initCacheUserVideo()
  // 设置默认下载目录
  downLoadPath.value = localStorage.getItem('downLoadPath')
})

onUnmounted(() => {
  clearInterval(timer.value)
})
</script>

<template>
  <div class="video-fusion-container">
    <!-- 视频融合表单 -->
    <el-card class="fusion-form-card">
      <div style="width: 100%; display: flex; justify-content: center">
        <el-form :model="fusionForm" label-width="120px" class="fusion-form">
          <!-- 上传视频1 -->
          <el-form-item label="上传视频1">
            <div class="upload-area">
              <el-upload
                class="video-upload"
                drag
                action="#"
                :auto-upload="false"
                :on-change="(file) => handleFileChange(file, 'video1')"
                :accept="'.mp4'"
                :show-file-list="false"
                :disabled="isLock"
              >
                <div class="upload-content">
                  <el-icon class="upload-icon" size="48" color="#6366f1">
                    <Upload />
                  </el-icon>
                  <div class="upload-text">
                    <p class="upload-title">点击或拖拽第一个视频文件到此处</p>
                    <p class="upload-subtitle">支持MP4视频格式</p>
                  </div>
                </div>
              </el-upload>
              <el-space>
                <el-checkbox :true-value="1" :false-value="0" @change="handleClickLock" v-model="isLock">锁定</el-checkbox>
              </el-space>
              <!-- 显示已选择的文件名 -->
              <div v-if="fusionForm.video1File" class="file-info">
                <el-tag type="success">{{ fusionForm.video1File.name }}</el-tag>
              </div>
              <div class="file-info" v-else-if="cacheUserVideos[userInfo.id]&&cacheUserVideos[userInfo.id].isLock && cacheUserVideos[userInfo.id].name">
                <el-tag type="success">{{ cacheUserVideos[userInfo.id]?.name }}</el-tag>
              </div>
            </div>
          </el-form-item>

          <!-- 上传视频2 -->
          <el-form-item label="上传视频2">
            <div class="upload-area">
              <el-upload
                class="video-upload"
                drag
                action="#"
                :auto-upload="false"
                :on-change="(file) => handleFileChange(file, 'video2')"
                :accept="'.mp4'"
                :show-file-list="false"
              >
                <div class="upload-content">
                  <el-icon class="upload-icon" size="48" color="#6366f1">
                    <Upload />
                  </el-icon>
                  <div class="upload-text">
                    <p class="upload-title">点击或拖拽第二个视频文件到此处</p>
                    <p class="upload-subtitle">支持MP4视频格式</p>
                  </div>
                </div>
              </el-upload>
              <!-- 显示已选择的文件名 -->
              <div v-if="fusionForm.video2File" class="file-info">
                <el-tag type="success">{{ fusionForm.video2File.name }}</el-tag>
              </div>
            </div>
          </el-form-item>

          <!-- 视频标题 -->
          <el-form-item label="视频输出目录">
            <div>{{downLoadPath}}</div>
            <el-button @click="openDirectoryDialog" style="margin-left: 10px;">打开目录</el-button>
            <!-- <el-input v-model="fusionForm.title" placeholder="请输入融合后的视频标题" /> -->
          </el-form-item>


          <!-- 操作按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              @click="handleVideoFusion"
              :loading="fusionLoading"
              size="large"
              style="width: 200px"
            >
              开始视频融合
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <videoPlayDialog ref="videoDialogRef" />
  </div>
</template>

<style lang="scss" scoped>
.video-fusion-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

/* 融合表单卡片 */
.fusion-form-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.fusion-form {
  width: 70%;
}

/* 文件上传区域 */
.upload-area {
  width: 100%;
}

.video-upload {
  width: 100%;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  text-align: center;
}

.upload-icon {
  margin-bottom: 16px;
}

.upload-text {
  color: #666;
}

.upload-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #1a1a1a;
}

.upload-subtitle {
  font-size: 14px;
  margin: 0;
  color: #999;
}

.file-info {
  margin-top: 10px;
  text-align: center;
}

/* 任务列表卡片 */
.task-list-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.task-header {
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.task-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

/* 进度条容器 */
.progress-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-text {
  font-size: 12px;
  color: #666;
  min-width: 35px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  padding: 6px;
  min-width: 32px;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 24px;
}

.el-select,
.el-input {
  width: 100%;
}

/* 上传组件样式 */
.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: auto;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.el-upload-dragger:hover {
  border-color: #6366f1;
  background-color: #f8f9ff;
}

/* 按钮样式 */
.el-button {
  border-radius: 6px;
  font-weight: 500;
}

.el-button--primary {
  background-color: #6366f1;
  border-color: #6366f1;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

/* 进度条样式 */
.el-progress {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-fusion-container {
    padding: 10px;
  }

  .fusion-form {
    width: 95%;
  }

  .upload-content {
    padding: 20px 15px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .progress-container {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
